//
//  DKDragButton.m
//  DanKU
//
//  Created by 蓝鳍互娱 on 2023/12/1.
//

#import "DKDragButton.h"
@interface DKDragButton()
//开始按下的触点坐标
@property (nonatomic, assign)CGPoint startPos;
@end
@implementation DKDragButton
-(instancetype)init{
    if(self = [super init]){
        self.backgroundColor = UIColor.clearColor;
        [self setBackgroundImage:DK_GetImage(@"dk_AuthKeFu") forState:UIControlStateNormal];
    }
    return self;
}
/**
 *  开始触摸，记录触点位置用于判断是拖动还是点击
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    // 获得触摸在根视图中的坐标
    UITouch *touch = [touches anyObject];
    _startPos = [touch locationInView:_rootView];
}
/**
 *  手指按住移动过程,通过悬浮按钮的拖动事件来拖动整个悬浮窗口
 */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获得触摸在根视图中的坐标
    UITouch *touch = [touches anyObject];
    CGPoint curPoint = [touch locationInView:_rootView];
    // 移动按钮到当前触摸位置
    self.center = curPoint;
}
/**
 *  拖动结束后使悬浮窗口吸附在最近的屏幕边缘
 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获得触摸在根视图中的坐标
    UITouch *touch = [touches anyObject];
    CGPoint curPoint = [touch locationInView:_rootView];
    // 通知代理,如果结束触点和起始触点极近则认为是点击事件
    if (pow((_startPos.x - curPoint.x),2) + pow((_startPos.y - curPoint.y),2) < 1) {
        if(self.tapDragBlock){
            self.tapDragBlock();
        }
    return;//点击后不吸附
    }
//    // 与四个屏幕边界距离
//    CGFloat left = curPoint.x;
//    CGFloat right = DK_SCREEN_W - curPoint.x;
//    // 计算四个距离最小的吸附方向
//    if(left > right){
        self.origin = CGPointMake(DK_SCREEN_W - self.width, DK_IsWidthScale(15)+DK_SafeAreaTop);
//    }else{
//        self.origin = CGPointMake(0, curPoint.y);
//    }
}

@end
